package cn.itcast.controller.cargo;

import cn.itcast.base.BaseController;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.FileUploadUtil;
import cn.itcast.utils.commons.UtilFuns;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;

    @Reference
    private FactoryService factoryService;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping(value = "/list", name = "合同下货物的分页数据查询")
    public String findAll(String contractId, @RequestParam(defaultValue = "1") int pageNum, @RequestParam("4") int pageSize) {
        // 查询指定合同下的货物 到页面展示
        ContractProductExample contractProductExample = new ContractProductExample();
        ContractProductExample.Criteria criteria = contractProductExample.createCriteria();
        //设置条件  （合同的id）
        criteria.andContractIdEqualTo(contractId);
        //查询
        PageInfo page = contractProductService.findAll(contractProductExample, pageNum, pageSize);
        request.setAttribute("page", page);

        // 生产货物的生产商家
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria factoryCriteria = factoryExample.createCriteria();
        factoryCriteria.andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", factoryList);
        // 带着合同id去页面
        request.setAttribute("contractId", contractId);
        return "cargo/product/product-list";

    }

    @RequestMapping(value = "/edit", name = "合同下货物的新增")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) throws Exception {
        // springmvc要玩上传：MultipartFile核心上传对象
        // 要求：1 属性名要和页面file的name属性名一致
        // 2 springmvc配置当前的核心上传对象


        //设置企业标识
        contractProduct.setCompanyId(companyId);
        //设置企业名称
        contractProduct.setCompanyName(companyName);

        if (UtilFuns.isEmpty(contractProduct.getId())) {
            // 将提交的图片上传到七牛云中
            String img = fileUploadUtil.upload(productPhoto);

            // 设置图片地址
            contractProduct.setProductImage("http://" + img);

            // 保存
            contractProductService.save(contractProduct);
        } else {
            contractProductService.update(contractProduct);
        }

        return "redirect: /cargo/contractProduct/list.do?contractId=" + contractProduct.getContractId();
    }

    @RequestMapping(value = "/toUpdate", name = "合同下货物编辑页面")
    public String toUpdate(String id) {
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct", contractProduct);
        //生产厂家
        FactoryExample factoryExample = new FactoryExample();
        FactoryExample.Criteria criteria = factoryExample.createCriteria();
        criteria.andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", factoryList);

        return "cargo/product/product-update";
    }

    @RequestMapping(value = "/delete", name = "合同下货物的删除")
    public String del(String id, String contractId) {
        // 根据货物的id删除货物
        contractProductService.delete(id);
        // 到最新页面展示最新数据
        return "redirect: /cargo/contractProduct/list.do?contractId=" + contractId;
    }


    @RequestMapping(value = "/import", name = "货物excel的上传")
    // 合同id  上传文件
    public String imports(String contractId, MultipartFile file) throws IOException {
        List<ContractProduct> list = new ArrayList<>();
        // 1 创建工作薄读取货物上传的excel表
        Workbook wb = new XSSFWorkbook(file.getInputStream());
        //2、选择工作页
        Sheet sheet = wb.getSheetAt(0);
        //3、读取excel表中的每一个数据封装给ContractProduct
        for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
            //读取每一行
            Row row = sheet.getRow(i);
            // 一行一个数组 用来保存当前行数的数据
            Object[] arr = new Object[row.getLastCellNum()];//表格内数据类型有string类型，有int类型，
            // 获取遍历每一行的总单元格
            for (int j = 1; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                if (cell != null) {
                    arr[j] = getCellValue(cell);// arr[1]=升华  arr[2]=xx001 arr[3]=1  arr[4]=PCS arr[5]=10

                }

            }
            ContractProduct contractProduct = new ContractProduct(arr, companyId, companyName);
            contractProduct.setContractId(contractId);
            list.add(contractProduct);
        }
        // 保存
        contractProductService.saveProductExcel(list);
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;
    }

    private Object getCellValue(Cell cell) {
        Object obj = null;
        CellType cellType = cell.getCellType();
        switch (cellType) {
            case STRING: { //字符串单元
                obj = cell.getStringCellValue();
                break;
            }
            //excel默认将日志也理解为数字
            case NUMERIC:{ //数字单元格
                if(DateUtil.isCellDateFormatted(cell)) { //日期
                    obj = cell.getDateCellValue();
                }else {
                    obj = cell.getNumericCellValue();
                }
                break;
            }
            case BOOLEAN:{ //boolean
                obj = cell.getBooleanCellValue();
                break;
            }
            default:{
                break;
            }
        }
//
        return obj;
    }


}

